package ch.ffhs.radarpp.web;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.AsyncTask;
import ch.ffhs.radarpp.model.Settings;

/**
 * 
 * @author Beda
 * 
 */
public class WebTask extends AsyncTask<Object, Integer, String> {

	private WebClient webClient;
	private WebParams webParams;
	private Settings appSettings;

	private Exception error;

	public WebTask(WebClient webClient, WebParams webParams, Settings appSettings) {
		this.webClient = webClient;
		this.webParams = webParams;
		this.appSettings = appSettings;
	}

	@Override
	protected String doInBackground(Object... params) {

		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpResponse response;
			
			String uri = "http://radarpp.lieger.org/" + webParams.getUri().replace(" ", "%20");
			
			if (webParams.getPostRequest() != null) {
				HttpPost post = new HttpPost(uri);
				post.setEntity(new ByteArrayEntity(webParams.getPostRequest().getBytes("UTF8")));
				response = httpclient.execute(post);
			} else {
				response = httpclient.execute(new HttpGet(uri));
			}

			StatusLine statusLine = response.getStatusLine();

			if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				response.getEntity().writeTo(out);
				out.close();
				String responseString = out.toString();

				return responseString;

			} else {
				// Closes the connection.
				response.getEntity().getContent().close();
				throw new IOException(statusLine.getReasonPhrase());
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
			error = e;
		} catch (IOException e) {
			e.printStackTrace();
			error = e;
		} catch (Exception e) {
			e.printStackTrace();
			error = e;
		}

		return null;
	}

	@Override
	protected void onPostExecute(String result) {

		if (error != null) {
			this.webClient.requestFailed(error, webParams.getContext());
		} else {
			this.webClient.requestCompleted(result, webParams.getContext());
		}
		super.onPostExecute(result);
	}

}
